Remove Invalid Parentheses

Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.

Note: The input string may contain letters other than the parentheses ( and ).

Examples:

  1. "()())()" -> ["()()()", "(())()"]
  2. "(a)())()" -> ["(a)()()", "(a())()"]
  3. ")(" -> [""]

Solution:

  1. public class Solution {
  2. public List<String> removeInvalidParentheses(String s) {
  3. List<String> res = new ArrayList<>();
  4. // sanity check
  5. if (s == null) return res;
  6. Set<String> visited = new HashSet<>();
  7. Queue<String> queue = new LinkedList<>();
  8. // initialize
  9. queue.add(s);
  10. visited.add(s);
  11. boolean found = false;
  12. while (!queue.isEmpty()) {
  13. s = queue.poll();
  14. if (isValid(s)) {
  15. // found an answer, add to the result
  16. res.add(s);
  17. found = true;
  18. }
  19. if (found) continue;
  20. // generate all possible states
  21. for (int i = 0; i < s.length(); i++) {
  22. // we only try to remove left or right paren
  23. if (s.charAt(i) != '(' && s.charAt(i) != ')') continue;
  24. String t = s.substring(0, i) + s.substring(i + 1);
  25. if (!visited.contains(t)) {
  26. // for each state, if it's not visited, add it to the queue
  27. queue.add(t);
  28. visited.add(t);
  29. }
  30. }
  31. }
  32. return res;
  33. }
  34. // helper function checks if string s contains valid parantheses
  35. boolean isValid(String s) {
  36. int count = 0;
  37. for (int i = 0; i < s.length(); i++) {
  38. char c = s.charAt(i);
  39. if (c == '(') count++;
  40. if (c == ')' && count-- == 0) return false;
  41. }
  42. return count == 0;
  43. }
  44. }